<?php

namespace app\admin\controller\cms;

use app\admin\model\cms\PlazaCategorymodel;
use app\api\controller\v2\Score;
use app\api\service\CommonService;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 广场-帖子管理
 *
 * @icon fa fa-circle-o
 */
class PlazaPost extends Backend
{

    /**
     * PlazaPostModel模型对象
     * @var \app\admin\model\cms\PlazaPostModel
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\cms\PlazaPostModel;
        $categoryList = PlazaCategorymodel::select();
        $this->view->assign("categoryList", $categoryList);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['category'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['replytime']  = $params['replytime'] ? : null;
        $checkUrl = $this->checkUrl($params['postcontent']);//根据url抓取文章
        if ($checkUrl['code'] == 200){
            $params['scraping_text_link'] = $checkUrl['scraping_text_link'];
            $params['postcontent'] = (new CommonService())->contentFiles($checkUrl['content']);//获取文章内容中的文件链接地址,将不是本项目的文件存到本项目中,并更新对应的文件地址
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            //置顶-调整积分
            $score = new Score();//调整积分

            //置顶
            if ($params['top'] == 1){
                //增加积分
                $score->editScore($params['user_id'],$this->model->id,'top_score',1,'plaza_post');
            }
            //加精
            if ($params['is_jing'] == 1){
                //增加积分
                $score->editScore($params['user_id'],$this->model->id,'highlight_score',1,'plaza_post');
            }
            //审核
            if ($params['is_audit'] == 1){
                //增加积分
                $score->editScore($params['user_id'],$this->model->id,'input_post_score',1,'plaza_post');
            }

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['replytime']  = $params['replytime'] ? : null;
        $checkUrl = $this->checkUrl($params['postcontent']);//根据url抓取文章
        if ($checkUrl['code'] == 200){
            $params['scraping_text_link'] = $checkUrl['scraping_text_link'];
            $params['postcontent'] = $checkUrl['content'];
        }

        //判断提交内容和旧的内容是否不同
        if ($row['postcontent'] != $params['postcontent']){
            $params['postcontent'] = (new CommonService())->contentFiles($params['postcontent']);//获取文章内容中的文件链接地址,将不是本项目的文件存到本项目中,并更新对应的文件地址
        }

        $result = false;

        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

            //调整积分
            $score = new Score();//调整积分
            if (isset($params['top'])){
                if ($params['top'] == 1){
                    //置顶增加积分
                    $score->editScore($params['user_id'],$row['id'],'top_score',1,'plaza_post');
                }else{
                    //置顶减少积分
                    $score->editScore($params['user_id'],$row['id'],'top_score',2,'plaza_post');
                }
            }
            //加精
            if (isset($params['is_jing'])){
                if ($params['is_jing'] == 1){
                    //增加积分
                    $score->editScore($params['user_id'],$row['id'],'highlight_score',1,'plaza_post');
                }else{
                    //减少积分
                    $score->editScore($params['user_id'],$row['id'],'highlight_score',2,'plaza_post');
                }
            }
            //审核
            if (isset($params['is_audit'])){
                if ($params['is_audit'] == 1){
                    //增加积分
                    $score->editScore($params['user_id'],$row['id'],'input_post_score',1,'plaza_post');
                }else{
                    //减少积分
                    $score->editScore($params['user_id'],$row['id'],'input_post_score',2,'plaza_post');
                }
            }

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 批量更新
     *
     * @param $ids
     * @return void
     */
    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }


        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        Db::startTrans();
        try {
            $score = new Score();//调整积分
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
                //审核
                if (isset($values['is_audit'])){
                    if ($values['is_audit'] == 1){
                        //发帖增加积分
                        $score->editScore($item['user_id'],$item['id'],'input_post_score',1,'plaza_post');
                    }else{
                        //发帖减少积分
                        $score->editScore($item['user_id'],$item['id'],'input_post_score',2,'plaza_post');
                    }
                }
                //置顶
                if (isset($values['top'])){
                    if ($values['top'] == 1){
                        //置顶增加积分
                        $score->editScore($item['user_id'],$item['id'],'top_score',1,'plaza_post');//取消发起置顶
                    }else{
                        //置顶减少积分
                        $score->editScore($item['user_id'],$item['id'],'top_score',2,'plaza_post');//取消发起置顶
                    }
                }
                //加精
                if (isset($values['is_jing'])){
                    if ($values['is_jing'] == 1){
                        //加精增加积分
                        $score->editScore($item['user_id'],$item['id'],'highlight_score',1,'plaza_post');
                    }else{
                        //加精减少积分
                        $score->editScore($item['user_id'],$item['id'],'highlight_score',2,'plaza_post');
                    }
                }
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

}
